package com.hup.utils.swing;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * @author hugan
 * @date 2019/12/10
 */
public class KeyBoardUtil {

    /**
     * 给组件添加按键监听;处理原生的坑
     */
    public static void listen(Component component, KeyListener listener) {
        component.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                //注意坑:只能监听type,否则在输入法激活时按esc也会进来
                int keyCode = KeyEvent.getExtendedKeyCodeForChar(e.getKeyChar());
                listener.onType(keyCode, e);
            }
        });
    }

    /**
     * 处理过keyCode的监听
     */
    public interface KeyListener {
        /**
         * @param keyCode 类似{@link KeyEvent#VK_ENTER}
         */
        void onType(int keyCode, KeyEvent e);
    }

}
